﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.SearchCriteria;

namespace NTQOnlineExam.Services.ReportService.Order
{
    public class GetOrderHistoryByUserDbCommand : ICommand<SearchResult<OrderDTO>>
    {
        private readonly int _userId;
        private readonly int _pageSize;
        private readonly int _pageIndex;
        private readonly IList<SearchSortItem> _sortItems;
        private const string _sql = @"
                WITH PAGING AS (
                    SELECT o.OrderId {1}, row_number() over (order by {0}) as rownumber
                    FROM dbo.[Order] o 
                  WHERE o.UserId = @UserId AND o.Status != @DraftStatus
                )
        ";

        public GetOrderHistoryByUserDbCommand(IList<SearchSortItem> sortItems, int userId, int pageSize, int pageIndex)
        {
            _pageSize = pageSize;
            _pageIndex = pageIndex;
            _userId = userId;
            _sortItems = sortItems;
        }

        public SearchResult<OrderDTO> Execute()
        {
            var connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            using (var connection = new SqlConnection(connectionString))
            {
                IList<OrderDTO> items = new List<OrderDTO>();
                int totalCount = 0;
                var cmd = new SqlCommand(BuildQuery(), connection);
                cmd.Parameters.Add("@PageIndex", SqlDbType.Int).Value = _pageIndex;
                cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = _pageSize;
                cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = _userId;
                cmd.Parameters.Add("@DraftStatus", SqlDbType.Int).Value = OrderStatus.Draft.GetHashCode();
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                try
                {
                    if (!reader.Read()) return null;
                    totalCount = reader.GetInt32(0);
                    reader.NextResult();

                    while (reader.Read())
                    {
                        items.Add(GetDto(reader));
                    }
                }
                finally
                {
                    reader.Close();
                }
                return new SearchResult<OrderDTO>(items, totalCount);
            }
        }

        private OrderDTO GetDto(SqlDataReader reader)
        {
            var order = new OrderDTO()
            {
                OrderUniqueId = (int)reader["OrderUniqueId"],
                OrderId = (Guid)reader["OrderId"],
            };
            order.SubTotal = reader.GetDecimal(reader.GetOrdinal("SubTotal"));
            order.CreationDate = reader.GetDateTime(reader.GetOrdinal("CreationDate"));
            order.Status = reader.GetInt32(reader.GetOrdinal("Status"));
            return order;
        }


        private string BuildQuery()
        {
            var query = new StringBuilder();
            var sqlCount = string.Format(_sql,BuildOrderClause(), string.Empty);
            var sqlQuery = string.Format(_sql, BuildOrderClause(), ", o.SubTotal, o.CreationDate, o.Status, o.OrderUniqueId");
            query.AppendFormat("{0} {1};{2} {3}", sqlCount, @"SELECT COUNT(1) FROM paging", sqlQuery, @" SELECT * FROM paging WHERE (@PageSize=0 or rownumber between @PageSize*@PageIndex+1 and @PageSize*(@PageIndex+1)) ORDER BY rownumber");
            return query.ToString();
        }


        private string BuildOrderClause()
        {
            var orderClause = new StringBuilder();
            foreach (SearchSortItem sortItem in _sortItems)
            {
                orderClause.AppendFormat("o.{0} {1}", sortItem.SortExpression, sortItem.SortOrder == SortOrder.Ascending ? "ASC" : "DESC");
                orderClause.Append(',');
            }

            if (orderClause.Length <= 0)
            {
                orderClause.Append("o.OrderUniqueId desc ");
            }
            else
            {
                orderClause.Remove(orderClause.Length - 1, 1);
            }
            return orderClause.ToString();
        }
    }
}
